/*
 * @Descripttion:
 * @version:
 * @Author: lfzxs@qq.com
 * @Date: 2025-06-30 15:40:00
 * @LastEditors: lfzxs@qq.com
 * @LastEditTime: 2025-06-30 17:46:07
 */
package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"

	"golang.org/x/text/encoding"
	"golang.org/x/text/encoding/japanese"
	"golang.org/x/text/encoding/korean"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/encoding/traditionalchinese"
	"golang.org/x/text/encoding/unicode"
)

// 获取编码器
func getEncoder(encodingName string) (encoding.Encoding, error) {
	switch strings.ToLower(encodingName) {
	case "utf8", "utf-8":
		return unicode.UTF8, nil
	case "gbk":
		return simplifiedchinese.GBK, nil
	case "gb18030":
		return simplifiedchinese.GB18030, nil
	case "big5":
		return traditionalchinese.Big5, nil
	case "euckr":
		return korean.EUCKR, nil
	case "eucjp":
		return japanese.EUCJP, nil
	case "shiftjis":
		return japanese.ShiftJIS, nil
	default:
		return nil, fmt.Errorf("不支持的编码格式: %s", encodingName)
	}
}

func main() {
	// 定义命令行参数
	dirPath := flag.String("dir", ".", "要扫描的目录路径")
	extension := flag.String("ext", ".txt", "要处理的文件扩展名")
	outputFile := flag.String("output", "output.txt", "输出的文本文件名")
	encoding := flag.String("encoding", "utf-8", "文件编码(utf-8, gbk, gb18030, big5, euckr, eucjp, shiftjis)")
	flag.Parse()

	// 获取编码器
	enc, err := getEncoder(*encoding)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// 创建输出文件
	outFile, err := os.Create(*outputFile)
	if err != nil {
		fmt.Printf("创建输出文件时发生错误: %v\n", err)
		os.Exit(1)
	}
	defer outFile.Close()

	// 遍历目录
	err = filepath.Walk(*dirPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		// 检查文件扩展名
		if !info.IsDir() && strings.HasSuffix(strings.ToLower(info.Name()), strings.ToLower(*extension)) {
			// 写入文件名
			_, err = fmt.Fprintln(outFile, info.Name())
			if err != nil {
				return err
			}

			// 写入空行
			_, err = fmt.Fprintln(outFile)
			if err != nil {
				return err
			}

			// 读取并写入文件内容
			file, err := os.Open(path)
			if err != nil {
				return err
			}
			defer file.Close()

			// 使用指定编码读取文件
			reader := enc.NewDecoder().Reader(file)
			scanner := bufio.NewReader(reader)

			for {
				line, err := scanner.ReadString('\n')
				if err != nil && err != io.EOF {
					return err
				}

				// 移除行尾的换行符
				line = strings.TrimRight(line, "\r\n")

				// 写入文本行
				if line != "" {
					_, err = fmt.Fprintln(outFile, line)
					if err != nil {
						return err
					}
				}

				if err == io.EOF {
					break
				}
			}

			// 在文件内容后添加额外的空行
			_, err = fmt.Fprintln(outFile)
			if err != nil {
				return err
			}
		}
		return nil
	})

	if err != nil {
		fmt.Printf("处理文件时发生错误: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("文本文件已成功生成: %s\n", *outputFile)
}
